package com.libl.controller;

import com.libl.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController//等价于 @ResponseBody 加 @Controller
public class UserController {
    @RequestMapping("/doLogin")
    //返回的结果对象result需要转换成jason给前端页面来展示，直接使用@RestController
    public Result login(String username, String password){

        //获取subject主体对象，包含了所有对外的接口
        Subject subject = SecurityUtils.getSubject();

        //创建token对象
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        //登录；执行realm，获取用户、角色、权限
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("未知的账户");
        } catch (LockedAccountException e) {
            e.printStackTrace();
            System.out.println("账户已锁定");
        } catch (CredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        } catch (AuthenticationException e) {//上面三个异常都是 AuthenticationException的子类，这个总异常要放在最后
            e.printStackTrace();
            System.out.println("其他认证问题");
        }

        if (subject.isAuthenticated()){
            System.out.println("登录成功");
        }

        //登陆成功返回一个结果对象，login方法返回void的话对于前端控制器来说会循环执行登录方法
        return new Result(0,"登陆成功");
    }
}
